#ifndef _TOOLS_M_SLEEP_H__
#define _TOOLS_M_SLEEP_H__


#include <stdint.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <sys/time.h>

static inline
void mSleep(uint32_t ms)
{
    uint32_t s = ms/1000;
    ms -= s*1000;
    sleep(s);
    usleep(ms*1000);
}

static inline
void uSleep(uint32_t us)
{
    uint32_t s = us/1000000;
    us -= s*1000000;

    if (s > 0) sleep(s);

    usleep(us);
}

/**
 * @brief getCurrentTime
 * @return utc时间 秒
 */
static  inline
time_t getCurrentTime(void)
{
    time_t tm;
    time(&tm);
    return tm;
}

static  inline
bool checkTime(time_t t0, time_t t1, size_t diff)
{
    if (t1 < t0)  // 时间倒流
        return true;
    t0 += diff;
    return (t0 <= t1);
}

static inline
void getSystime(struct tm &tm)
{
    time_t rawtime;
    time( &rawtime );

    memcpy(&tm, localtime( &rawtime ), sizeof(struct tm));
}

static inline
void getSystemTime(struct tm &tm)
{
    return getSystime(tm);
}

static inline
struct tm * getSystemTime(void)
{
    time_t rawtime;
    time( &rawtime );

    return localtime(&rawtime);
}

static inline
uint64_t getMilliseconds()
{
    uint64_t milliseconds = 0;
    struct timeval tv;
    gettimeofday(&tv, NULL);
    milliseconds = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
    return milliseconds;
}

static inline
std::string logTime(void)
{
    std::string fmt;
    char buf[128] = {0};
    struct timespec tsCurr;
    struct tm tmCurr;
    int usCurr;
    clock_gettime(CLOCK_REALTIME, &tsCurr);
    localtime_r(&tsCurr.tv_sec, &tmCurr);
    usCurr = tsCurr.tv_nsec / 1000;
    sprintf(buf,"%04u-%02u-%02u %02u:%02u:%02u.%06u",
            tmCurr.tm_year + 1900,
            tmCurr.tm_mon + 1,
            tmCurr.tm_mday,
            tmCurr.tm_hour,
            tmCurr.tm_min,
            tmCurr.tm_sec,
            usCurr);
    fmt.append(buf);
    return fmt;
}

#endif
